//
//  registerViewController.m
//  忘不了
//
//  Created by rimi on 16/7/8.
//  Copyright © 2016年 handuan. All rights reserved.
//

#import "registerViewController.h"
#import "SDAutoLayout.h"
#import "BaseRequest.h"
#import "UserModel.h"
#import "CheckWeb.h"
@interface registerViewController ()<UITextFieldDelegate>
@property (nonatomic,strong)UIImageView *headPhoto;
@property (nonatomic,strong)UILabel *name;
@property (nonatomic,strong)UILabel *password;
@property (nonatomic,strong)UILabel *surePassword;
@property (nonatomic,strong)UILabel *email;
@property (nonatomic,strong)UITextField *nameText;
@property (nonatomic,strong)UITextField *passwordText;
@property (nonatomic,strong)UITextField *surePasswordText;
@property (nonatomic,strong)UITextField *emailText;
@property (nonatomic,strong)UIButton *registerButton;
@property (nonatomic,strong)UILabel *tipLabel;
@end

@implementation registerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
                                                         forBarMetrics:UIBarMetricsDefault];//隐藏导航栏返回按钮自带的文字
    self.title = @"注册";
    //设置导航栏标题颜色、字体大小等
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20],NSForegroundColorAttributeName:[UIColor brownColor]}];
    
    UIImageView *backGroudView = [[UIImageView alloc]initWithFrame:self.view.frame];
    backGroudView.image = [UIImage imageNamed:@"s.jpg"];
    [self.view addSubview:backGroudView];
    
    [self initInterFace];
    
}

- (void)initInterFace {
        _name = [[UILabel alloc]init];
    _name.text = @"账       号:";
    _name.textAlignment = NSTextAlignmentRight;
    _name.textColor = [UIColor brownColor];
    _name.font = [UIFont systemFontOfSize:20];
    [_name sizeToFit];
    [self.view addSubview:_name];
    _name.sd_layout
    .widthRatioToView(self.view,0.3)
    .heightIs(40)
    .leftSpaceToView(self.view,5)
    .topSpaceToView(self.view,self.view.bounds.size.height * 0.25);
    
    _password = [[UILabel alloc]init];
    _password.text = @"密       码:";
    _password.textAlignment = NSTextAlignmentRight;
    _password.textColor = [UIColor brownColor];
    _password.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:_password];
    _password.sd_layout
    .widthRatioToView(self.view,0.3)
    .heightIs(40)
    .leftSpaceToView(self.view,5)
    .topSpaceToView(_name,20);
    
    _surePassword = [[UILabel alloc]init];
    _surePassword.text = @"确认密码:";
    _surePassword.textAlignment = NSTextAlignmentRight;
    _surePassword.textColor = [UIColor brownColor];
    _surePassword.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:_surePassword];
    _surePassword.sd_layout
    .widthRatioToView(self.view,0.3)
    .heightIs(40)
    .leftSpaceToView(self.view,5)
    .topSpaceToView(_password,20);
    
    _email = [[UILabel alloc]init];
    _email.text = @"邮       箱:";
    _email.textAlignment = NSTextAlignmentRight;
    _email.textColor = [UIColor brownColor];
    _email.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:_email];
    _email.sd_layout
    .widthRatioToView(self.view,0.3)
    .heightIs(40)
    .leftSpaceToView(self.view,5)
    .topSpaceToView(_surePassword,20);
    
    _nameText = [[UITextField alloc]init];
    _nameText.placeholder = @"6到15位";
    _nameText.textColor = [UIColor blackColor];
    _nameText.font = [UIFont systemFontOfSize:20];
    _nameText.layer.cornerRadius = 10;
    _nameText.layer.masksToBounds = YES;
    _nameText.clearButtonMode = UITextFieldViewModeWhileEditing;
    _nameText.backgroundColor = [UIColor whiteColor];
    _nameText.delegate = self;
    [self.view addSubview:_nameText];
    _nameText.sd_layout
    .leftSpaceToView(_name,5)
    .topEqualToView(_name)
    .rightSpaceToView(self.view,20)
    .heightRatioToView(_name,1);
    
    _passwordText = [[UITextField alloc]init];
    _passwordText.placeholder = @"6到15位";
    _passwordText.textColor = [UIColor blackColor];
    _passwordText.secureTextEntry = YES;
    _passwordText.font = [UIFont systemFontOfSize:20];
    _passwordText.layer.cornerRadius = 10;
    _passwordText.layer.masksToBounds = YES;
    _passwordText.clearButtonMode = UITextFieldViewModeWhileEditing;
    _passwordText.backgroundColor = [UIColor whiteColor];
    _passwordText.delegate = self;
    [self.view addSubview:_passwordText];
    _passwordText.sd_layout
    .leftSpaceToView(_password,5)
    .topEqualToView(_password)
    .rightSpaceToView(self.view,20)
    .heightRatioToView(_password,1);
    
    _surePasswordText = [[UITextField alloc]init];
    _surePasswordText.placeholder = @"6到15位";
    _surePasswordText.textColor = [UIColor blackColor];
    _surePasswordText.secureTextEntry = YES;
    _surePasswordText.font = [UIFont systemFontOfSize:20];
    _surePasswordText.layer.cornerRadius = 10;
    _surePasswordText.layer.masksToBounds = YES;
    _surePasswordText.clearButtonMode = UITextFieldViewModeWhileEditing;
    _surePasswordText.backgroundColor = [UIColor whiteColor];
    _surePasswordText.delegate = self;
    [self.view addSubview:_surePasswordText];
    _surePasswordText.sd_layout
    .leftSpaceToView(_surePassword,5)
    .topEqualToView(_surePassword)
    .rightSpaceToView(self.view,20)
    .heightRatioToView(_surePassword,1);
    
    _emailText = [[UITextField alloc]init];
    _emailText.placeholder = @"xxx@xx.com";
    _emailText.textColor = [UIColor blackColor];
    _emailText.font = [UIFont systemFontOfSize:20];
    _emailText.layer.cornerRadius = 10;
    _emailText.layer.masksToBounds = YES;
    _emailText.clearButtonMode = UITextFieldViewModeWhileEditing;
    _emailText.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_emailText];
    _emailText.sd_layout
    .leftSpaceToView(_email,5)
    .topEqualToView(_email)
    .rightSpaceToView(self.view,20)
    .heightRatioToView(_email,1);
    
    _tipLabel = [[UILabel alloc]init];
    _tipLabel.alpha = 0;
    _tipLabel.text = @"";
    _tipLabel.textAlignment = NSTextAlignmentCenter;
    _tipLabel.textColor = [UIColor redColor];
    _tipLabel.font = [UIFont systemFontOfSize:18];
    [self.view addSubview:_tipLabel];
    _tipLabel.sd_layout
    .leftEqualToView(_email)
    .rightEqualToView(_emailText)
    .topSpaceToView(_emailText,15)
    .heightRatioToView(_emailText,0.7);
    
    _registerButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [_registerButton setTitle:@"注册" forState:UIControlStateNormal];
    [_registerButton setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
    _registerButton.backgroundColor = [UIColor colorWithRed:0.8784 green:0.8431 blue:0.7765 alpha:1.0];
    _registerButton.layer.cornerRadius = 10;
    _registerButton.layer.masksToBounds = YES;
    _registerButton.layer.borderWidth = 1;
    _registerButton.layer.borderColor = [UIColor colorWithRed:0.7569 green:0.7333 blue:0.5333 alpha:1.0].CGColor;
    [_registerButton addTarget:self action:@selector(registerButtonTaped) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_registerButton];
    _registerButton.sd_layout
    .centerXIs(self.view.frame.size.width/2)
    .bottomSpaceToView(self.view,self.view.frame.size.width*0.1)
    .leftSpaceToView(self.view,120)
    .rightSpaceToView(self.view,120)
    .heightRatioToView(_email,1);
    
}

- (void)registerButtonTaped {
    //匹配字母和数字、下划线
    NSString *regex = @"[a-zA-Z0-9_\u4e00-\u9fa5]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    if ([_nameText.text  isEqual: @""] || [_passwordText.text  isEqual: @""] || [_surePasswordText.text  isEqual: @""] || [_emailText.text  isEqual: @""]) {
        UIAlertController *tips = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请填写完整" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [tips addAction:sure];
        [self presentViewController:tips animated:YES completion:nil];
    } else if (![pred evaluateWithObject:_nameText.text] || ![pred evaluateWithObject:_passwordText.text] || ![pred evaluateWithObject:_surePasswordText.text] || _nameText.text.length < 6 || _passwordText.text.length < 6 || _surePasswordText.text.length < 6) {
        UIAlertController *tips = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"账号、密码长度需为6到15位，且只能由下划线、字母或数字组成" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [tips addAction:sure];
        [self presentViewController:tips animated:YES completion:nil];
    } else if (_passwordText.text != _surePasswordText.text) {
        _tipLabel.alpha = 1;
        _tipLabel.text = @"两次输入密码不一致";
        [self performSelector:@selector(disappear) withObject:nil afterDelay:1.0];
    } else if ([self isValidateEmail:self.emailText.text] == NO){
        _tipLabel.alpha = 1;
        _tipLabel.text = @"邮箱输入错误";
        [self performSelector:@selector(disappear) withObject:nil afterDelay:1.0];
    } else {
        BOOL isWeb = [CheckWeb checkWang];
        if (isWeb == NO) {
            _tipLabel.alpha = 1;
            _tipLabel.text = @"请检查网络";
            [self performSelector:@selector(disappear) withObject:nil afterDelay:2.0];
        }else{
            [BaseRequest startRegisterWithUserName:self.nameText.text password:self.passwordText.text email:self.emailText.text completionhanlder:^(Response *response) {
                if (response.isSuccess) {
                    UIAlertController *tips = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"注册成功" preferredStyle:UIAlertControllerStyleAlert];
                    [self presentViewController:tips animated:YES completion:nil];
                    [self performSelector:@selector(dismiss) withObject:nil afterDelay:2.0];
                    
                    //存储账号密码
                    [[UserModel shareUserModel] storeUserName:_nameText.text Password:_passwordText.text];
                    [self autoLogin];
                } else {
                    _tipLabel.alpha = 1;
                    _tipLabel.text = [NSString stringWithFormat:@"%@",response.resultObject];
                    [self performSelector:@selector(disappear) withObject:nil afterDelay:2.0];
                }
            }];
            
        }
    }
}

//自动登录
- (void)autoLogin {
    NSDictionary *userInfo = [[UserModel shareUserModel] readUserNameAndPassword];
    [BaseRequest startLoginWithUserName:userInfo[@"username"] password:userInfo[@"password"] completionhanlder:^(Response *response) {
        if (response.isSuccess) {
            NSLog(@"自动登录成功");
            [UserModel shareUserModel].isLogin = YES;
        }else{
            NSLog(@"自动登录失败");
        }
    }];
}
//文本框限定最大长度
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (range.location >= 15) {
        return NO;
    }
    return YES;
}

//正则表达式验证邮箱
- (BOOL)isValidateEmail:(NSString *)email{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

//dismiss 警告提示框
- (void)dismiss
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)disappear {
    _tipLabel.alpha = 0;
    _tipLabel.text = @"";
    [self dismissViewControllerAnimated:YES completion:nil];
}

//点空白回收键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

@end
